import { useState, useEffect } from 'react';
import { Header } from '../components/Header';
import { Footer } from '../components/Footer';
import { ImageWithLoading } from '../components/ImageWithLoading';
import { ChevronRight, X, ChevronLeft } from 'lucide-react';
import { useParams, Link } from 'react-router-dom';

export const ProductListPage = () => {
  const { categorySlug } = useParams<{ categorySlug: string }>();
  const [currentPage, setCurrentPage] = useState(1);
  const [activeFilters, setActiveFilters] = useState<{
    category: string;
    brand: string[];
    price: string;
    rating: string;
  }>({
    category: categorySlug || 'blood-pressure-monitors',
    brand: [],
    price: '',
    rating: ''
  });

  // Category mappings
  const categoryInfo = {
    'blood-pressure-monitors': {
      title: 'Blood Pressure Monitors',
      description: 'Find the perfect blood pressure monitor for home use from our expert-tested selection',
      imagePlaceholder: 'https://picsum.photos/600/400?random=1'
    },
    'nebulizers': {
      title: 'Nebulizers', 
      description: 'Reliable respiratory therapy devices for all ages and conditions',
      imagePlaceholder: 'https://picsum.photos/600/400?random=2'
    },
    'mobility-aids': {
      title: 'Mobility Aids',
      description: 'Support devices for independence and safe movement',
      imagePlaceholder: 'https://picsum.photos/600/400?random=3'
    },
    'first-aid': {
      title: 'First Aid Kits',
      description: 'Essential emergency supplies and first aid equipment',
      imagePlaceholder: 'https://picsum.photos/600/400?random=4'
    },
    'thermometers': {
      title: 'Digital Thermometers',
      description: 'Fast and accurate temperature measurement devices',
      imagePlaceholder: 'https://picsum.photos/600/400?random=5'
    },
    'vision-care': {
      title: 'Vision Care',
      description: 'Products to support eye health and comfort',
      imagePlaceholder: 'https://picsum.photos/600/400?random=6'
    },
    'heart-rate-monitors': {
      title: 'Heart Rate Monitors',
      description: 'Track your cardiac health during rest and activity',
      imagePlaceholder: 'https://picsum.photos/600/400?random=7'
    },
    'medication-management': {
      title: 'Medication Management',
      description: 'Tools to organize and track medications',
      imagePlaceholder: 'https://picsum.photos/600/400?random=8'
    }
  };

  const currentCategory = categoryInfo[categorySlug as keyof typeof categoryInfo] || categoryInfo['blood-pressure-monitors'];

  useEffect(() => {
    setActiveFilters(prev => ({ ...prev, category: categorySlug || 'blood-pressure-monitors' }));
    setCurrentPage(1);
  }, [categorySlug]);

  // Mock data for products based on category
  const generateProducts = (category: string) => {
    const categoryKey = category as keyof typeof categoryInfo;
    const categoryData = categoryInfo[categoryKey] || categoryInfo['blood-pressure-monitors'];
    
    // Real product names for different categories
    const productNames: { [key: string]: string[] } = {
      'blood-pressure-monitors': [
        'Omron Platinum Blood Pressure Monitor',
        'Beurer BM55 Upper Arm Monitor',
        'iHealth Track Smart Monitor',
        'Withings BPM Connect Wi-Fi',
        'Omron HeartGuide Wearable',
        'Beurer BM67 Bluetooth Monitor',
        'iHealth Feel Wireless Monitor',
        'Withings BPM Core Advanced',
        'Omron Gold Blood Pressure Monitor',
        'Beurer BM85 Touch Screen Monitor',
        'iHealth Clear Wireless Monitor',
        'Withings BPM Connect Compact'
      ],
      'glucose-meters': [
        'OneTouch Verio Reflect Meter',
        'Accu-Chek Guide Me Meter',
        'FreeStyle Libre 2 System',
        'Dexcom G6 Continuous Monitor',
        'OneTouch Ultra 2 Meter',
        'Accu-Chek Aviva Plus Meter',
        'FreeStyle Freedom Lite',
        'Contour Next EZ Meter',
        'OneTouch Verio IQ Meter',
        'Accu-Chek SmartView Meter',
        'FreeStyle InsuLinx Meter',
        'Contour Next One Smart'
      ],
      'thermometers': [
        'Braun ThermoScan 7 Ear Thermometer',
        'Temporal Artery Thermometer TAT-5000',
        'Kinsa Smart Ear Thermometer',
        'iHealth No-Touch Forehead Thermometer',
        'Braun Forehead Thermometer BFH175',
        'Exergen Temporal Scanner TAT-2000C',
        'Kinsa QuickCare Digital Thermometer',
        'iHealth PT3 Smart Thermometer',
        'Braun Digital Stick Thermometer',
        'Temporal Artery Pro 4000 Scanner',
        'Kinsa Smart Stick Thermometer',
        'iHealth Align Forehead Thermometer'
      ],
      'pulse-oximeters': [
        'Masimo MightySat Rx Pulse Oximeter',
        'Nonin Onyx Vantage 9590 Oximeter',
        'Zacurate Pro Series 500DL',
        'ChoiceMMed MD300C2 Oximeter',
        'Masimo Rad-5v Handheld Oximeter',
        'Nonin GO2 Achieve Oximeter',
        'Zacurate Pro Series 500D',
        'ChoiceMMed MD300C15D Oximeter',
        'Masimo Radius-7 Wearable',
        'Nonin WristOx2 Model 3150',
        'Zacurate Digital Fingertip',
        'ChoiceMMed Handheld MD300M'
      ],
      'heart-rate-monitors': [
        'Polar H10 Heart Rate Sensor',
        'Garmin HRM-Pro Plus Monitor',
        'Wahoo TICKR X Heart Rate Monitor',
        'Polar Verity Sense Optical',
        'Garmin HRM-Dual Heart Rate Strap',
        'Wahoo TICKR FIT Armband',
        'Polar H9 Heart Rate Sensor',
        'Garmin HRM-Swim Swimming Monitor',
        'Wahoo TICKR Heart Rate Monitor',
        'Polar OH1+ Optical Sensor',
        'Garmin HRM-Run Running Dynamics',
        'Wahoo TICKR X Heart Rate Strap'
      ],
      'scales': [
        'Withings Body+ Smart Scale',
        'Fitbit Aria Air Smart Scale',
        'Eufy Smart Scale P2 Pro',
        'RENPHO Body Fat Scale',
        'Withings Body Cardio Scale',
        'Fitbit Aria 2 Wi-Fi Scale',
        'Eufy Smart Scale C1',
        'RENPHO Premium Smart Scale',
        'Withings Body Scan Scale',
        'Fitbit Aria Air Digital Scale',
        'Eufy Smart Scale P1',
        'RENPHO Bluetooth Body Scale'
      ],
      'nebulizers': [
        'Philips Respironics InnoSpire Essence',
        'Omron CompAir Elite NE-C30',
        'Pari LC Plus Reusable Nebulizer',
        'Philips Sidestream Disposable',
        'Omron MicroAir U100 Portable',
        'Pari Trek S Portable Nebulizer',
        'Philips Respironics OptiChamber',
        'Omron CompAir Pro NE-C28P',
        'Pari Baby Nebulizer Mask',
        'Philips InnoSpire Deluxe',
        'Omron Portable Mesh Nebulizer',
        'Pari LC Sprint Reusable'
      ],
      'mobility-aids': [
        'Drive Medical Four Wheel Rollator',
        'Hugo Mobility Quadpod Cane',
        'Medline Steel Folding Commode',
        'Drive DeVilbiss Blue Streak Wheelchair',
        'Hugo Elite Rollator Walker',
        'Medline Guardian Toilet Safety Rail',
        'Drive Medical Red Dot Cane',
        'Hugo Adjustable Quad Cane',
        'Medline Basic Rollator Walker',
        'Drive DeVilbiss Sentra EC Wheelchair',
        'Hugo Mobility Carbon Fiber Cane',
        'Medline Steel Drop Arm Commode'
      ],
      'first-aid': [
        'Johnson & Johnson All-Purpose First Aid Kit',
        'Adventure Medical Kits Ultralight',
        'Be Smart Get Prepared 250 Piece Kit',
        'Johnson & Johnson Red Cross Kit',
        'Adventure Medical Mountain Series',
        'Be Smart Get Prepared Travel Kit',
        'Johnson & Johnson Portable Kit',
        'Adventure Medical Kits Sportsman',
        'Be Smart Get Prepared Home Kit',
        'Johnson & Johnson Family Kit',
        'Adventure Medical Kits Weekender',
        'Be Smart Get Prepared Office Kit'
      ],
      'vision-care': [
        'Bausch + Lomb Biotrue ONEday',
        'Acuvue Oasys 1-Day with HydraLuxe',
        'Alcon Dailies Total1 Contact Lenses',
        'Bausch + Lomb Ultra Contact Lenses',
        'Acuvue Vita Monthly Contact Lenses',
        'Alcon Air Optix Night & Day',
        'Bausch + Lomb PureVision2 HD',
        'Acuvue Oasys with Transitions',
        'Alcon Precision1 Daily Contacts',
        'Bausch + Lomb Infuse Contact Lenses',
        'Acuvue Moist 1-Day Contact Lenses',
        'Alcon FreshLook ColorBlends'
      ],
      'medication-management': [
        'PillPack Smart Pill Dispenser',
        'Hero Health Smart Dispenser',
        'PillTime Multi-Alarm Dispenser',
        'Medisafe Pill Reminder App',
        'PillPack Weekly Pill Organizer',
        'Hero Health Automatic Dispenser',
        'PillTime Digital Reminder',
        'Medisafe Smart Pill Box',
        'PillPack Monthly Organizer',
        'Hero Health Voice Reminder',
        'PillTime Travel Dispenser',
        'Medisafe Caregiver App'
      ]
    };

    const names = productNames[categoryKey] || productNames['blood-pressure-monitors'];
    
    return Array(12).fill(null).map((_, index) => ({
      id: `${category}-${index + 1}`,
      name: names[index] || `${names[0]} Pro ${index + 1}`,
      image: `https://picsum.photos/400/300?random=${category}-${index + 50}`,
      price: Math.floor(Math.random() * 100) + 50,
      rating: Number((Math.random() * 2 + 3).toFixed(1)),
      reviewCount: Math.floor(Math.random() * 500) + 50,
      brand: ['Omron', 'Beurer', 'iHealth', 'Withings'][Math.floor(Math.random() * 4)]
    }));
  };

  const products = generateProducts(activeFilters.category);
  const itemsPerPage = 6;
  const totalPages = Math.ceil(products.length / itemsPerPage);
  const displayedProducts = products.slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage);
  const brands = ['Omron', 'Beurer', 'iHealth', 'Withings'];
  const priceRanges = ['Under $50', '$50-$100', '$100-$200', 'Over $200'];
  const ratings = ['4 Stars & Up', '3 Stars & Up', '2 Stars & Up'];
  const toggleBrandFilter = (brand: string) => {
    if (activeFilters.brand.includes(brand)) {
      setActiveFilters({
        ...activeFilters,
        brand: activeFilters.brand.filter(b => b !== brand)
      });
    } else {
      setActiveFilters({
        ...activeFilters,
        brand: [...activeFilters.brand, brand]
      });
    }
    setCurrentPage(1);
  };
  const clearFilters = () => {
    setActiveFilters({
      ...activeFilters,
      brand: [],
      price: '',
      rating: ''
    });
    setCurrentPage(1);
  };
  return (
    <div className="flex flex-col min-h-screen w-full bg-white">
      <Header />
      <main className="flex-grow">
        {/* Breadcrumb */}
        <div className="bg-gray-50 py-3">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-center text-sm text-gray-500">
              <Link to="/" className="hover:text-[#0e4c92]">
                Home
              </Link>
              <ChevronRight className="h-4 w-4 mx-2" />
              <Link to="/categories" className="hover:text-[#0e4c92]">
                Categories
              </Link>
              <ChevronRight className="h-4 w-4 mx-2" />
              <span className="text-gray-700 font-medium">
                {currentCategory.title}
              </span>
            </div>
          </div>
        </div>
        {/* Header */}
        <div className="bg-white pt-6 pb-4">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <h1 className="text-3xl font-bold text-[#0e4c92]">
              {currentCategory.title}
            </h1>
            <p className="mt-2 text-gray-600">
              {currentCategory.description}
            </p>
          </div>
        </div>
        {/* Product grid with sidebar */}
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          <div className="flex flex-col lg:flex-row gap-8">
            {/* Filters sidebar */}
            <div className="w-full lg:w-64 flex-shrink-0">
              <div className="bg-white border border-gray-200 rounded-lg p-4">
                <div className="flex items-center justify-between mb-4">
                  <h2 className="font-medium text-lg text-gray-900">Filters</h2>
                  {(activeFilters.brand.length > 0 || activeFilters.price || activeFilters.rating) && <button onClick={clearFilters} className="text-sm text-[#5cb8b2] hover:text-[#0e4c92]">
                      Clear all
                    </button>}
                </div>
                {/* Brand filter */}
                <div className="py-4 border-t border-gray-200">
                  <h3 className="font-medium text-gray-900">Brand</h3>
                  <div className="mt-2 space-y-2">
                    {brands.map(brand => <div key={brand} className="flex items-center">
                        <input id={`brand-${brand}`} name={`brand-${brand}`} type="checkbox" className="h-4 w-4 text-[#0e4c92] focus:ring-[#5cb8b2] border-gray-300 rounded" checked={activeFilters.brand.includes(brand)} onChange={() => toggleBrandFilter(brand)} />
                        <label htmlFor={`brand-${brand}`} className="ml-2 text-gray-700">
                          {brand}
                        </label>
                      </div>)}
                  </div>
                </div>
                {/* Price filter */}
                <div className="py-4 border-t border-gray-200">
                  <h3 className="font-medium text-gray-900">Price</h3>
                  <div className="mt-2 space-y-2">
                    {priceRanges.map(range => <div key={range} className="flex items-center">
                        <input id={`price-${range}`} name="price" type="radio" className="h-4 w-4 text-[#0e4c92] focus:ring-[#5cb8b2] border-gray-300" checked={activeFilters.price === range} onChange={() => {
                      setActiveFilters({
                        ...activeFilters,
                        price: range
                      });
                      setCurrentPage(1);
                    }} />
                        <label htmlFor={`price-${range}`} className="ml-2 text-gray-700">
                          {range}
                        </label>
                      </div>)}
                  </div>
                </div>
                {/* Rating filter */}
                <div className="py-4 border-t border-gray-200">
                  <h3 className="font-medium text-gray-900">Rating</h3>
                  <div className="mt-2 space-y-2">
                    {ratings.map(rating => <div key={rating} className="flex items-center">
                        <input id={`rating-${rating}`} name="rating" type="radio" className="h-4 w-4 text-[#0e4c92] focus:ring-[#5cb8b2] border-gray-300" checked={activeFilters.rating === rating} onChange={() => {
                      setActiveFilters({
                        ...activeFilters,
                        rating: rating
                      });
                      setCurrentPage(1);
                    }} />
                        <label htmlFor={`rating-${rating}`} className="ml-2 text-gray-700">
                          {rating}
                        </label>
                      </div>)}
                  </div>
                </div>
              </div>
            </div>
            {/* Product grid */}
            <div className="flex-grow">
              <div className="flex justify-between items-center mb-6">
                <p className="text-gray-600">
                  Showing {(currentPage - 1) * itemsPerPage + 1}-
                  {Math.min(currentPage * itemsPerPage, products.length)} of{' '}
                  {products.length} products
                </p>
                <div className="flex items-center">
                  <span className="mr-2 text-gray-600 text-sm">Sort by:</span>
                  <select className="border border-gray-300 rounded px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-[#5cb8b2] focus:border-[#5cb8b2]">
                    <option>Recommended</option>
                    <option>Price: Low to High</option>
                    <option>Price: High to Low</option>
                    <option>Highest Rated</option>
                  </select>
                </div>
              </div>
              {/* Active filters */}
              {(activeFilters.brand.length > 0 || activeFilters.price || activeFilters.rating) && <div className="flex flex-wrap items-center gap-2 mb-6">
                  <span className="text-sm text-gray-700 font-medium">
                    Active filters:
                  </span>
                  {activeFilters.brand.map(brand => <span key={brand} className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-[#e6f7f5] text-[#0e4c92]">
                      {brand}
                      <button type="button" className="ml-1 flex-shrink-0" onClick={() => toggleBrandFilter(brand)}>
                        <X className="h-3 w-3" />
                      </button>
                    </span>)}
                  {activeFilters.price && <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-[#e6f7f5] text-[#0e4c92]">
                      {activeFilters.price}
                      <button type="button" className="ml-1 flex-shrink-0" onClick={() => setActiveFilters({
                  ...activeFilters,
                  price: ''
                })}>
                        <X className="h-3 w-3" />
                      </button>
                    </span>}
                  {activeFilters.rating && <span className="inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-[#e6f7f5] text-[#0e4c92]">
                      {activeFilters.rating}
                      <button type="button" className="ml-1 flex-shrink-0" onClick={() => setActiveFilters({
                  ...activeFilters,
                  rating: ''
                })}>
                        <X className="h-3 w-3" />
                      </button>
                    </span>}
                </div>}
              {/* Products */}
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {displayedProducts.map(product => (
                  <Link 
                    key={product.id} 
                    to={`/product/${product.id}`} 
                    className="group border border-gray-200 rounded-lg overflow-hidden hover:shadow-md transition-shadow"
                  >
                    <div className="aspect-w-4 aspect-h-3">
                      <ImageWithLoading src={product.image} alt={product.name} className="w-full h-48 object-cover" />
                    </div>
                    <div className="p-4">
                      <h3 className="text-lg font-medium text-gray-900 group-hover:text-[#0e4c92]">
                        {product.name}
                      </h3>
                      <p className="mt-1 text-lg font-semibold text-[#0e4c92]">
                        ${product.price}
                      </p>
                      <div className="mt-2 flex items-center">
                        <div className="flex items-center">
                          {[0, 1, 2, 3, 4].map(rating => (
                            <svg 
                              key={rating} 
                              className={`h-5 w-5 ${product.rating > rating ? 'text-yellow-400' : 'text-gray-200'}`} 
                              fill="currentColor" 
                              viewBox="0 0 20 20"
                            >
                              <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
                            </svg>
                          ))}
                        </div>
                        <p className="ml-2 text-sm text-gray-600">
                          {product.rating} ({product.reviewCount} reviews)
                        </p>
                      </div>
                      <p className="mt-2 text-sm text-gray-500">
                        {product.brand}
                      </p>
                    </div>
                  </Link>
                ))}
              </div>
              {/* Pagination */}
              <div className="mt-8 flex items-center justify-between">
                <div className="flex-1 flex justify-between sm:hidden">
                  <button onClick={() => setCurrentPage(Math.max(1, currentPage - 1))} disabled={currentPage === 1} className="relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50">
                    Previous
                  </button>
                  <button onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))} disabled={currentPage === totalPages} className="ml-3 relative inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50">
                    Next
                  </button>
                </div>
                <div className="hidden sm:flex-1 sm:flex sm:items-center sm:justify-center">
                  <div>
                    <nav className="relative z-0 inline-flex rounded-md shadow-sm -space-x-px" aria-label="Pagination">
                      <button onClick={() => setCurrentPage(Math.max(1, currentPage - 1))} disabled={currentPage === 1} className="relative inline-flex items-center px-2 py-2 rounded-l-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
                        <span className="sr-only">Previous</span>
                        <ChevronLeft className="h-5 w-5" />
                      </button>
                      {Array.from({
                      length: totalPages
                    }).map((_, index) => {
                      const pageNumber = index + 1;
                      return <button key={pageNumber} onClick={() => setCurrentPage(pageNumber)} className={`relative inline-flex items-center px-4 py-2 border text-sm font-medium ${currentPage === pageNumber ? 'z-10 bg-[#0e4c92] border-[#0e4c92] text-white' : 'bg-white border-gray-300 text-gray-700 hover:bg-gray-50'}`}>
                            {pageNumber}
                          </button>;
                    })}
                      <button onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))} disabled={currentPage === totalPages} className="relative inline-flex items-center px-2 py-2 rounded-r-md border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50">
                        <span className="sr-only">Next</span>
                        <ChevronRight className="h-5 w-5" />
                      </button>
                    </nav>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </main>
      <Footer />
    </div>
  );
};